<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规则编号" prop="ruleCode">
        <el-input
          v-model="queryParams.ruleCode"
          placeholder="请输入规则编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xs:creditRule:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['xs:creditRule:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="creditRuleList" @selection-change="handleSelectionChange" border>
      <el-table-column label="规则编号" align="center" prop="ruleCode">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['xs:creditRule:query']"
          >{{scope.row.ruleCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="超额目标" align="center" prop="excessTarget" />
      <el-table-column label="超额奖金" align="center" prop="excessBonus" />
      <el-table-column label="提成方式" align="center" prop="commissionWay" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xs:creditRule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xs:creditRule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改业绩规则配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="规则编号" prop="ruleCode">
              <el-input v-model="form.ruleCode" placeholder="请输入规则编号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleName">
              <el-input v-model="form.ruleName" placeholder="请输入规则名称" :readonly="optType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="超额目标" prop="excessTarget">
              <el-input-number
                :min="0"
                :step="0.01"
                v-model="form.excessTarget"
                placeholder="请输入超额目标"
                :disabled="optType === 'view'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="超额奖金" prop="excessBonus">
              <el-input-number
                :min="0"
                :step="0.01"
                v-model="form.excessBonus"
                placeholder="请输入超额奖金"
                :disabled="optType === 'view'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="提成方式" prop="commissionWay">
              <el-select v-model="form.commissionWay" placeholder="请选择提成方式" :disabled="optType === 'view'" >
                <el-option label="统一提成" value="统一提成" />
                <el-option label="阶梯提成" value="阶梯提成" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用员工" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请选择适用员工" readonly>
                <el-button slot="append" @click="handleSelectUser" icon="el-icon-search" v-if="optType !== 'view'"></el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
            </el-form-item>
          </el-col>
        </el-row>

        <commissionLine
          ref="line"
          :ruleId="form.id"
          :commissionWay="form.commissionWay"
          :optType="optType"
          v-if="form.id !== null"
          @revertCommissionWay="revertCommissionWay"
        ></commissionLine>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType !== 'view'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCreditRule,
  getCreditRule,
  delCreditRule,
  addCreditRule,
  updateCreditRule
} from "@/api/mes/xs/creditRule";
import { genCode } from "@/api/system/autocode/rule";
import UserSelect from "@/components/userSelect/multi.vue";
import commissionLine from "./line.vue"

export default {
  name: "CreditRule",
  components: { UserSelect, commissionLine },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 业绩规则配置表格数据
      creditRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleCode: null,
        ruleName: null,
        excessTarget: null,
        excessBonus: null,
        commissionWay: null,
        userId: null,
        userName: null,
        nickName: null,
        deptId: null,
        sex: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ruleCode: [
          { required: true, message: "规则编号不能为空", trigger: "blur" }
        ],
        ruleName: [
          { required: true, message: "规则名称不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "适用员工不能为空", trigger: "blur" }
        ],
        commissionWay: [
          { required: true, message: "提成方式不能为空", trigger: "change" }
        ]
      },
      // 显隐开关
      optType: 'add',


    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询业绩规则配置列表 */
    getList() {
      this.loading = true;
      listCreditRule(this.queryParams).then(response => {
        this.creditRuleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ruleCode: null,
        ruleName: null,
        excessTarget: null,
        excessBonus: null,
        commissionWay: null,
        userId: null,
        userName: null,
        nickName: null,
        deptId: null,
        sex: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('CREDIT_RULE_CODE').then(response =>{
        this.form.ruleCode = response;
      });
      this.open = true;
      this.title = "添加业绩规则配置";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCreditRule(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改业绩规则配置";
        this.optType = "update";
      });
    },
    /** 查看按钮操作 **/
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getCreditRule(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看业绩规则配置";
        this.optType = "view";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCreditRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCreditRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除业绩规则配置编号为"' + ids + '"的数据项？').then(function() {
        return delCreditRule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xs/creditRule/export', {
        ...this.queryParams
      }, `creditRule_${new Date().getTime()}.xlsx`)
    },
    // 员工选择点击
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 员工选择回显
    onUserSelected(rows) {
      if(rows != null){
        for (let i = 0; i < rows.length; i++) {
          if (i === rows.length - 1) {
            this.form.userId = this.form.userId + rows[i].userId;
            this.form.userName = this.form.userName + rows[i].userName;
            this.form.nickName = this.form.nickName + rows[i].nickName;
            this.form.deptId = this.form.deptId + rows[i].deptId;

          }else {
            this.form.userId = (this.form.userId == null ? "" : this.form.userId) + rows[i].userId + ",";
            this.form.userName = (this.form.userName == null ? "" : this.form.userName) + rows[i].userName + ",";
            this.form.nickName = (this.form.nickName == null ? "" : this.form.nickName) + rows[i].nickName + ",";
            this.form.deptId = (this.form.deptId == null ? "" : this.form.deptId) + rows[i].deptId + ",";

          }
        }
      }

    },
    // 恢复commissionWay的值
    revertCommissionWay(oldVal) {
      this.form.commissionWay = oldVal;
    },


  }
};
</script>
